package org.fing.edu.uy.esbadp.motor.strategies;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;

import org.fing.edu.uy.esbadp.core.AdpFlowInterface;
import org.fing.edu.uy.esbadp.core.AdpFlowRBAL;
import org.fing.edu.uy.esbadp.core.entity.DMRegisteredService;
import org.fing.edu.uy.esbadp.core.entity.GenericTreeNode;
import org.fing.edu.uy.esbadp.core.entity.PropertiesMonitoring;
import org.fing.edu.uy.esbadp.core.interfaces.IAdpStrategy;
import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.fing.edu.uy.esbadp.motor.comunication.AdmAdaptationComunication;

public class AdpStrategyBalanceLoadService implements IAdpStrategy{

	private static final java.util.logging.Logger logger = LoggerADP.getLogger(AdpStrategyBalanceLoadService.class.getSimpleName());

	/*
	 * 				   -> 									originalService 													-> 	
	 * 
	 * 				   -> S_ToCanonical-> S1_FromCanonical -> equivalenVvirtualService1 -> S1_ToCanonical -> S_FromCanonical 	-> 
	 * 			       -> ...
	 * FlowTree = RBAL -> S_ToCanonical-> Si_FromCanonical -> equivalenVirtualServicei -> Si_ToCanonical -> S_FromCanonical		-> 
	 * 				   -> ...
	 * 				   -> S_ToCanonical-> SN_FromCanonical -> equivalenVirtualServiceN -> SN_ToCanonical -> S_FromCanonical		->
	 */
	@Override
	public GenericTreeNode<AdpFlowInterface> getAdpTree(DMRegisteredService service,List<DMRegisteredService> equivServices,PropertiesMonitoring properties) {
		try{	
			GenericTreeNode<AdpFlowInterface> treeNode = new GenericTreeNode<AdpFlowInterface>();	
			AdpFlowInterface list = new AdpFlowRBAL();
			treeNode.setData(list);		
						
			for(DMRegisteredService equivalent: equivServices){
				AdpStrategyEquivalentService equivalentStrategy = new AdpStrategyEquivalentService(); 
				List<DMRegisteredService> equivalentList = new LinkedList<DMRegisteredService>();
				equivalentList.add(equivalent);
				GenericTreeNode<AdpFlowInterface> branch = equivalentStrategy.getAdpTree(service, equivalentList, properties);					
				treeNode.addChild(branch);
			}
			
			if (treeNode.getChildren().size() > 0){
				GenericTreeNode<AdpFlowInterface> virtualServiceNode = AdmAdaptationComunication.getAdpNodeForInvokeVirtualService(service);
				if (virtualServiceNode != null){
					treeNode.addChild(virtualServiceNode);
					return treeNode;
				}else{
					logger.log(Level.SEVERE, "Error in getAdpNodeForInvokeVirtualService");
					return null;
				}					
			}else{	
				return null;
			}

		}catch(Exception ex){
			logger.log(Level.SEVERE, "Exception in AdpStrategyBalanceLoadService...\n StackTarce => [ {0} ]", ex);	
			return null;
		}
	}
	
}
